package com.wtp.wallpaper.rabbitmq.config;

import com.rabbitmq.client.ConnectionFactory;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.DefaultClassMapper;
import org.springframework.amqp.support.converter.DefaultJackson2JavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.core.Binding;

@Configuration
public class RabbitMQConfig {

//    @Bean
//    public MessageConverter jsonMessageConverter() {
//        DefaultClassMapper classMapper = new DefaultClassMapper();
//        classMapper.setTrustedPackages("com.wtp.wallpaper.rabbitmq.data");
//        Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
//        converter.setClassMapper(classMapper);
//        return converter;
//    }

//    @Bean
//    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
//        RabbitTemplate template = new RabbitTemplate(connectionFactory);
//        template.setMessageConverter(jsonMessageConverter());
//        return template;
//    }

    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
        DefaultJackson2JavaTypeMapper typeMapper = new DefaultJackson2JavaTypeMapper();
        typeMapper.setTrustedPackages("com.wtp.wallpaper.rabbitmq.data"); // 信任目标类所在包
        converter.setJavaTypeMapper(typeMapper);
        //converter.setAlwaysConvertToInferredType(true);
        return converter;
    }

    // 声明交换机
    @Bean
    public DirectExchange ratingExchange() {
        return new DirectExchange("rating.exchange");
    }

    // 声明队列
    @Bean
    public Queue ratingQueue() {
        return new Queue("rating.queue", true);  // 持久化队列
    }

    // 绑定队列和交换机
    @Bean
    public Binding ratingBinding(Queue ratingQueue, DirectExchange ratingExchange) {
        return BindingBuilder.bind(ratingQueue).to(ratingExchange).with("rating.routing.key");
    }

//    @Bean
//    public Jackson2JsonMessageConverter jsonMessageConverter() {
//        Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
//        DefaultJackson2JavaTypeMapper typeMapper = new DefaultJackson2JavaTypeMapper();
//        typeMapper.setTrustedPackages("com.wtp.wallpaper.pojo.dto"); // 允许的包名或类
//        converter.setJavaTypeMapper(typeMapper);
//        return converter;
//    }

    @Bean
    public Queue esSyncQueue() {
        return new Queue("es.sync.queue");
    }

}
